package com.zl.autocode.service.autocode.impl;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zl.autocode.common.constant.AutocodeEnum;
import com.zl.autocode.common.constant.AutocodeProperties;
import com.zl.autocode.dao.autocode.ZLCfgGenerateMapper;
import com.zl.autocode.dao.autocode.ZlTemplateDtlMapper;
import com.zl.autocode.dao.autocode.ZlTemplateMapper;
import com.zl.autocode.dto.autocode.template.ReqTemplateAddDTO;
import com.zl.autocode.dto.autocode.template.ReqTemplateDelDTO;
import com.zl.autocode.dto.autocode.template.ReqTemplateDetailDTO;
import com.zl.autocode.dto.autocode.template.ReqTemplateEditDTO;
import com.zl.autocode.dto.autocode.template.ReqTemplateQueryDTO;
import com.zl.autocode.dto.autocode.template.ReqTemplateStateDTO;
import com.zl.autocode.dto.autocode.template.ResTemplateAddDTO;
import com.zl.autocode.dto.autocode.template.ResTemplateDelDTO;
import com.zl.autocode.dto.autocode.template.ResTemplateDetailDTO;
import com.zl.autocode.dto.autocode.template.ResTemplateEditDTO;
import com.zl.autocode.dto.autocode.template.ResTemplateQueryDTO;
import com.zl.autocode.dto.autocode.template.ResTemplateStateDTO;
import com.zl.autocode.dto.autocode.template.ResTemplateVO2;
import com.zl.autocode.entity.autocode.ZlTemplate;
import com.zl.autocode.entity.autocode.po.ZlTemplateVo;
import com.zl.autocode.service.autocode.ITemplateService;
import com.zl.autocode.service.base.AutocodeBaseManager;
import com.zl.common.dto.ReqDTO;
import com.zl.common.dto.pagination.PageReqVO;
import com.zl.common.enums.resp.GlobalRespEnum;
import com.zl.common.exception.BizException;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;

/**
 * 模板信息
 * @author ZL
 */
@Service("autocodeTemplateService")
public class TemplateServiceImpl extends AutocodeBaseManager implements ITemplateService {

    @Autowired
    private ZlTemplateMapper templateMapper;
    @Autowired
    private ZlTemplateDtlMapper templateDtlMapper;
    @Autowired
    private AutocodeProperties autocodeProperties;
    @Autowired
    private ZLCfgGenerateMapper cfgGenerateMapper;
    
    @Override
    public ResTemplateQueryDTO queryTemplateList(ReqDTO<ReqTemplateQueryDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateQueryDTO reqData = reqInfo.getReqData();
        PageReqVO page = pageHandle(reqInfo.getPageInfo());//处理分页数据
        ResTemplateQueryDTO resDTO = BeanUtil.copyProperties(page, ResTemplateQueryDTO.class);
        if(StringUtils.isNotBlank(reqData.getTemplateTitle())){
            reqData.setTemplateTitle("%"+reqData.getTemplateTitle()+"%");
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap = BeanUtil.beanToMap(reqData);
        
        Page<Object> pageHp = PageHelper.startPage(page.getPage(), page.getLimit(),page.getSortorder());
        List<ZlTemplateVo> list = templateMapper.selectListPage(paramMap);
        resDTO.setData(BeanUtil.copyToList(list, ResTemplateVO2.class));
        resDTO.setCount(pageHp.getTotal());
        
        return resDTO;
    }
    
    @Override
    public ResTemplateDetailDTO queryTemplateDetail(ReqDTO<ReqTemplateDetailDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateDetailDTO reqData = reqInfo.getReqData();
        ResTemplateDetailDTO res = new ResTemplateDetailDTO();
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap = BeanUtil.beanToMap(reqData);
        ZlTemplate view = templateMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(view, res);
        return res;
    }
    
    @Override
    public ResTemplateAddDTO insertTemplateInfo(ReqDTO<ReqTemplateAddDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateAddDTO reqData = reqInfo.getReqData();
        ResTemplateAddDTO res = new ResTemplateAddDTO();
        Date time = getSystemTime().getDate();
        
        ZlTemplate record = new ZlTemplate();
        BeanUtil.copyProperties(reqData, record);
        
        initCreateInfo(record, reqInfo, time);
        record.setTemplateId(IdUtil.simpleUUID());
        record.setTemplatePath(filePath(autocodeProperties.getAutocodePathMajor(),autocodeProperties.getAutocodePathTemplate()
                ,new String[]{record.getTemplateId()}));
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("templateId",record.getTemplateId());
        //检查主键是否冲突
        if(templateMapper.countExistKey(paramMap)>0){
            throw new BizException(GlobalRespEnum.DUPLICATE_PRIMARY_KEY);
        }
        
        templateMapper.insertSelective(record);
        
        ZlTemplate keyInfo = templateMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
    
    @Override
    public ResTemplateEditDTO updateTemplateInfo(ReqDTO<ReqTemplateEditDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateEditDTO reqData = reqInfo.getReqData();
        ResTemplateEditDTO res = new ResTemplateEditDTO();
        Date time = getSystemTime().getDate();
        
        ZlTemplate record = new ZlTemplate();
        BeanUtil.copyProperties(reqData, record);
        
        initUpdateInfo(record, reqInfo, time);
        
        templateMapper.updateByPrimaryKeySelective(record);
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("templateId",record.getTemplateId());
        ZlTemplate keyInfo = templateMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
    
    @Override
    public ResTemplateDelDTO deleteTemplateInfo(ReqDTO<ReqTemplateDelDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateDelDTO reqData = reqInfo.getReqData();
        ResTemplateDelDTO res = new ResTemplateDelDTO();
        Date time = getSystemTime().getDate();
        
        Map<String,Object> paramMap = BeanUtil.beanToMap(reqData);
        if(templateDtlMapper.countExistKey(paramMap) > 0 || cfgGenerateMapper.countExistKey(paramMap) > 0){
            throw new BizException(GlobalRespEnum.DELETION_NOT_ALLOWED);
        }
        ZlTemplate template = templateMapper.selectOneByMap(paramMap);
        if(StringUtils.isNotBlank(template.getTemplatePath())
                && template.getTemplatePath().contains(autocodeProperties.getAutocodePathMajor()) 
                && template.getTemplatePath().contains(autocodeProperties.getAutocodePathTemplate())){
            FileUtil.del(handlerRootPath(template.getTemplatePath()));
        }
        templateMapper.deleteByMap(paramMap);
        
        return res;
    }
    
    @Override
    public ResTemplateStateDTO updateTemplateState(ReqDTO<ReqTemplateStateDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateStateDTO reqData = reqInfo.getReqData();
        ResTemplateStateDTO res = new ResTemplateStateDTO();
        Date time = getSystemTime().getDate();
         
        ZlTemplate record = new ZlTemplate();
        BeanUtil.copyProperties(reqData, record);
        initUpdateInfo(record, reqInfo, time);
        templateMapper.updateByPrimaryKeySelective(record);
         
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("templateId",record.getTemplateId());
        ZlTemplate keyInfo = templateMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
    
    @Override
    public ResTemplateDelDTO deleteTemplateAndDetail(ReqDTO<ReqTemplateDelDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateDelDTO reqData = reqInfo.getReqData();
        ResTemplateDelDTO res = new ResTemplateDelDTO();
        Date time = getSystemTime().getDate();
        
        Map<String,Object> paramMap = BeanUtil.beanToMap(reqData);
        ZlTemplate template = templateMapper.selectOneByMap(paramMap);
        if(StringUtils.isNotBlank(template.getTemplatePath())
                && template.getTemplatePath().contains(autocodeProperties.getAutocodePathMajor()) 
                && template.getTemplatePath().contains(autocodeProperties.getAutocodePathTemplate())){
            FileUtil.del(handlerRootPath(template.getTemplatePath()));
        }
        templateMapper.deleteByMap(paramMap);
        templateDtlMapper.deleteByMap(paramMap);
        
        return res;
    }
}